<template>
  <div>
    <!-- 上传资源对话框 -->
    <el-dialog title="上传资源" v-model="dialogVisible" width="500px" custom-class="upload-dialog" @close="handleClose">
      <el-form :model="uploadForm" :rules="uploadRules" label-width="80px" ref="formRef">
        <el-form-item label="资源名称" prop="name">
          <el-input v-model="uploadForm.name" placeholder="请输入资源名称" />
        </el-form-item>

        <el-form-item label="资源分类" prop="category">
          <el-select v-model="uploadForm.category" placeholder="请选择分类">
            <el-option v-for="category in categories" :key="category.id" :label="category.label"
              :value="category.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="资源类型" prop="isFree">
          <el-radio-group v-model="uploadForm.isFree">
            <el-radio :label="1">免费</el-radio>
            <el-radio :label="0">付费</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="网盘地址" prop="panPath">
          <el-input v-model="uploadForm.panPath" placeholder="请输入网盘地址" />
        </el-form-item>

        <el-form-item label="提取码" prop="panCode">
          <el-input v-model="uploadForm.panCode" placeholder="请输入提取码" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="submitUpload" :loading="uploading">
            确 定
          </el-button>
        </div>
      </template>

    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, toRefs, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { useAuthStore } from '@/store/index';
import { addResourceApi } from '@/api/resources';

// 定义props和emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  categories: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:visible']);

// 响应式数据
const uploading = ref(false);
const formRef = ref(null);

// 表单数据和验证规则
const uploadForm = reactive({
  name: '',
  category: '',
  isFree: 1,
  panPath: '',
  panCode: ''
});

const uploadRules = reactive({
  name: [
    { required: true, message: '请输入资源名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择资源分类', trigger: 'change' }
  ],
  isFree: [
    { required: true, message: '请选择资源类型', trigger: 'change' }
  ],
  panPath: [
    { required: true, message: '请输入网盘地址', trigger: 'blur' }
  ],
  panCode: [
    { required: true, message: '请输入提取码', trigger: 'blur' }
  ]
});

// 计算属性：双向绑定visible
const dialogVisible = computed({
  get() {
    return props.visible;
  },
  set(value) {
    emit('update:visible', value);
  }
});

// 监听对话框显示状态变化
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    resetForm(); // 关闭对话框时重置表单
  }
});

// 用户信息store
const authStore = useAuthStore();

// 重置表单
const resetForm = () => {
  Object.keys(uploadForm).forEach(key => {
    uploadForm[key] = key === 'isFree' ? 1 : ''; // 重置为默认值
  });
  if (formRef.value) {
    formRef.value.resetFields(); // 重置表单验证状态
  }
};

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false;
  emit('update:visible', dialogVisible.value);
  resetForm();
};

// 提交上传
const submitUpload = () => {
  if (!authStore.userInfo) {
    ElMessage.warning('请先登录');
    return;
  }

  formRef.value.validate((valid) => {
    if (valid) {
      uploading.value = true;
      addResourceApi(uploadForm)
        .then(() => {
          ElMessage.success('资源上传成功，等待博主审核！');
          handleClose();
        })
        .catch((error) => {
          ElMessage.error(error.message || '上传失败，请重试');
        })
        .finally(() => {
          uploading.value = false;
        });
    }
  });
};
</script>

<style scoped lang="scss">
:deep(.el-input__inner) {
  height: 44px;
  font-size: 14px;
  border: none !important;

  &::placeholder {
    color: #9ca3af;
  }
}

:deep(.el-input__prefix) {
  left: 12px;
  color: #6b7280;
}
</style>